package com.bjpowernode.service.impl;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.manager.RedisManager;
import com.bjpowernode.mapper.TRoleMapper;
import com.bjpowernode.mapper.TUserMapper;
import com.bjpowernode.model.TRole;
import com.bjpowernode.model.TUser;
import com.bjpowernode.query.BaseQuery;
import com.bjpowernode.query.UserQuery;
import com.bjpowernode.service.UserService;
import com.bjpowernode.util.CacheUtils;
import com.bjpowernode.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	private TUserMapper userMapper;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Resource
	private TRoleMapper roleMapper;
	@Autowired
	private RedisManager redisManager;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		TUser user = userMapper.selectByLoginAct(username);
		if (user == null) {
			throw new UsernameNotFoundException("登录账号不存在！");
		}
		
		// 查询一下当前用户的角色
	   List<TRole> userRoleList = roleMapper.selectRoleByUid(user.getId());
	   List<String> stringRoleLis = new ArrayList<String>();
	   userRoleList.forEach(role ->{
		   stringRoleLis.add(role.getRole());
	   });
	   
	   user.setRoleList(stringRoleLis);
	   
		return user;
	}

	@Override
	public PageInfo<TUser> getUserByPage(Integer current) {

		// 1.设置PageHelper
		PageHelper.startPage(current, Constants.PAGE_SIZE);

		// 2.查询
		List<TUser> userList = userMapper.selectUserByPage(BaseQuery.builder().build());

		// 3.封装分页数据到PageInfo
		PageInfo<TUser> info = new PageInfo<TUser>(userList);

		return info;
	}

	@Override
	public TUser getUserDetailById(Integer id) {

		if (id == null) {
			throw new RuntimeException("用户id不能为空");
		}
		return userMapper.selectUserDetailById(id);
	}

	@Override
	public int save(UserQuery userQuery) {
		TUser user = new TUser();

		BeanUtils.copyProperties(userQuery, user);

		// 密码加密
		user.setLoginPwd(passwordEncoder.encode(user.getLoginPwd()));
		// 设置创建人
		Integer loginId = JWTUtils.parseJWTByUserId(userQuery.getToken());
		user.setCreateBy(loginId);
		// 设置创建时间
		user.setCreateTime(new Date());
		return userMapper.insertSelective(user);

	}

	@Override
	public int update(UserQuery userQuery) {

		TUser user = new TUser();
		BeanUtils.copyProperties(userQuery, user);

		// 如果密码不为空
		if (StringUtils.hasText(userQuery.getLoginPwd())) {
			// 密码加密
			user.setLoginPwd(passwordEncoder.encode(user.getLoginPwd()));
		}

		// 设置修改人
		Integer loginId = JWTUtils.parseJWTByUserId(userQuery.getToken());
		user.setEditBy(loginId);
		user.setEditTime(new Date());

		return userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public int removeUser(Integer id) {
		int result = 0;
		TUser user = userMapper.selectByPrimaryKey(id);
		if (user != null) {
			result = userMapper.deleteByPrimaryKey(id);
		}
		return result;
	}

	@Override
	public int batchRemoveUser(List<String> userIdList) {
		return userMapper.deleteByIds(userIdList);
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List<TUser> queryOwner() {
		return (List<TUser>) CacheUtils.getCacheData(() -> {
			// 生产者，redis查询
			return redisManager.getValue(Constants.REDIS_OWNER_KEY);

		}, () -> {
			// 生产者，从mysql查询数据
			return userMapper.selectOwner();

		}, (t) -> {
			// 消费，把数据放入缓存redis
			redisManager.setValue(Constants.REDIS_OWNER_KEY, t);
		});
	}

}
